package com.example.fangwei.utilsapp.common_util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;

/**
 * 对bitmap进行操作的工具类
 * Created by fangw on 2018/5/14.
 */

public class BitmapUtil {

    private static final String TAG = BitmapUtil.class.getSimpleName();


    /**
     * 读取资源id到Bitmap
     * @param context 上下文对象
     * @param resId 资源ID
     * @return bitmap
     */
    public static Bitmap readBitmap(Context context,int resId){

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        options.inPurgeable = true;
        options.inInputShareable = true;
        InputStream inputStream = context.getResources().openRawResource(resId);

        return BitmapFactory.decodeStream(inputStream,null,options);
    }


    /**
     * 读取文件到Bitmap
     * @param path 文件路径
     * @return bitmap
     */
    public static Bitmap readBitmap(String path){

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        options.inPurgeable = true;
        options.inInputShareable = true;

        return BitmapFactory.decodeFile(path, options);
    }


    /**
     * bitmap 转 byte[]
     * @param bitmap bitmap
     * @return byte[]
     */
    public static byte[] bitmapToByte(Bitmap bitmap){
        ByteArrayOutputStream baos = null;

        if(null != bitmap && !bitmap.isRecycled()){
            try{

                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG,100,baos);

                if(baos.toByteArray() != null){
                    return baos.toByteArray();
                }

            }catch(Exception e){
                e.printStackTrace();
            }finally{
                closeCloseable(baos);
            }
            return null;
        }else {
            return null;
        }
    }



    /**
     * 压缩图片到指定byte大小 (在保证质量的情况下尽可能压缩 不保证压缩到指定字节)
     * @param datas 图片byte格式
     * @param byteCount 指定压缩到字节数
     * @return 压缩后的byte[] (不保证压缩到指定字节)
     */
    public static byte[] compressBitmap(byte[] datas, int byteCount) {
        boolean isFinish = false;
        if(datas != null && datas.length > byteCount) {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            Bitmap tmpBitmap = BitmapFactory.decodeByteArray(datas, 0, datas.length);
            int times = 1;
            double percentage = 1.0D;

            while(!isFinish && times <= 10) {
                percentage = Math.pow(0.8D, (double)times);
                int compress_datas = (int)(100.0D * percentage);
                tmpBitmap.compress(Bitmap.CompressFormat.JPEG, compress_datas, outputStream);
                if(outputStream != null && outputStream.size() < byteCount) {
                    isFinish = true;
                } else {
                    outputStream.reset();
                    ++times;
                }
            }

            if(outputStream != null) {
                byte[] outputStreamByte = outputStream.toByteArray();
                if(!tmpBitmap.isRecycled()) {
                    tmpBitmap.recycle();
                }

                if(outputStreamByte.length > byteCount) {
                    Log.e(TAG, "compressBitmap cannot compress to " + byteCount + ", after compress size=" + outputStreamByte.length);
                }

                return outputStreamByte;
            }
        }

        return datas;
    }



    /**
     * 统一关闭Closeable对象的方法 减少冗余的代码
     * @param closeable 可关闭的Closeable对象
     */
    private  static void closeCloseable(Closeable closeable) {
        try {
            if (null != closeable) {
                closeable.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG, "closeCloseable has been failed  == "+ e.getMessage() );
        }
    }

}
